package com.meiqiongproperty.yiguanjia.fragment.shopcart;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;

import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.activity.GenericFragmentActivity;
import com.meiqiongproperty.yiguanjia.commom.ViewConstant;
import com.meiqiongproperty.yiguanjia.databinding.ShopCartLayoutBinding;
import com.meiqiongproperty.yiguanjia.db.utils.ShopingCartUtils;
import com.meiqiongproperty.yiguanjia.fragment.BaseFragment;
import com.meiqiongproperty.yiguanjia.fragment.home.shopping.bean.ShopLocalListBean;
import com.meiqiongproperty.yiguanjia.fragment.shopcart.shopcartAdapter.ShopCartListAdapter;
import com.meiqiongproperty.yiguanjia.httpbean.evenBus.SelectedPrice;
import com.meiqiongproperty.yiguanjia.httpbean.evenBus.SeletedEvent;
import com.meiqiongproperty.yiguanjia.httpbean.shopcart.ShopCartListBean;
import com.meiqiongproperty.yiguanjia.httpbean.shopcart.ShoppingCarBean;
import com.meiqiongproperty.yiguanjia.utils.LogUtil;
import com.meiqiongproperty.yiguanjia.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * @version V1.0
 * @packge com.meiqiongproperty.yiguanjia.fragment.home
 * @UserChenJing
 * @Date2017/4/22
 */

public class CartFragment extends BaseFragment {
    public HashMap<Integer, Boolean> map = new HashMap<>();
    ShopCartLayoutBinding binding;
    ShopCartListAdapter adapter;
    List<ShopCartListBean> list_shopcart = new ArrayList<>();
    HashMap<Integer, Integer> shopcartAmountMap = new HashMap<Integer, Integer>();
    private boolean isChange = false;
    private EventBus event;
    ArrayList<ShoppingCarBean> data;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.shop_cart_layout, container, false);
        binding.setClick(this);
        event = EventBus.getDefault();
        init();
        event.register(this);

        return binding.getRoot();
    }

    private void init() {
        binding.navigation.setTitle("购物车");
        if (ViewConstant.hideLeft == 0) {
            if (isAdded()){
                binding.navigation.setBackgroundColor(getActivity().getResources().getColor(R.color.order_header_color));
            }
            binding.navigation.hideLeft(true);
        } else if (ViewConstant.hideLeft == 1) {
            if (isAdded()){
                binding.navigation.setBackgroundColor(getActivity().getResources().getColor(R.color.header_color));
            }
            binding.navigation.hideLeft(false);
        }

        binding.navigation.setLeftClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendKeyBackEvent();
            }
        });

        data = ShopingCartUtils.getAll(getActivity());
//        Toast.makeText(getActivity(), data.size() + "", Toast.LENGTH_SHORT).show();

        for (int i = 0; i < data.size(); i++) {
            ShopCartListBean bean = new ShopCartListBean();
            bean.setShopCartTitle(data.get(i).getProduct_title());
            bean.setShopCartAmount(data.get(i).getProduct_count());
            bean.setShopCartPrice(data.get(i).getProduct_price());
            bean.setShopCartImgUrl(data.get(i).getProduct_image());
            bean.setShopProductId(data.get(i).getProduct_id());
            bean.setShopCartOPrice(data.get(i).getProduct_oprice());
            list_shopcart.add(bean);
            shopcartAmountMap.put(i, 1);
        }

        adapter = new ShopCartListAdapter(getActivity(), list_shopcart, shopcartAmountMap, event);
        final LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerShopCart.setLayoutManager(manager);
        binding.recyclerShopCart.setAdapter(adapter);
        ((SimpleItemAnimator) binding.recyclerShopCart.getItemAnimator()).setSupportsChangeAnimations(false);
        adapter.notifyDataSetChanged();

        adapter.setCallback(new ShopCartListAdapter.ShopCartAmountCallback() {
            @Override
            public void refreshAmount(int pos, boolean isAdd) {
                adapter.setShopCartAmount(pos, isAdd);
            }
        });

        binding.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                try {
                    double sum = 0.00;
                    for (int i = 0; i < list_shopcart.size(); i++) {
                        if (isChecked) {
                            map.put(i, true);
                            sum += adapter.calculateItemPrice(i, Double.parseDouble(list_shopcart.get(i).getShopCartPrice()));
                        } else {
                            sum = 0;
                            map.put(i, false);
                            adapter.getList_price().set(i, 0.00);
                        }
                    }
                    adapter.setMap(map);
                    binding.tvTotalprice.setText("￥" + Utils.numberPointTwo(sum));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void onEventMainThread(SeletedEvent event) {
        int size = event.getSize();
        List<Double> list = adapter.getList_price();
        double sum = 0.0;
        for (Double price : list) {
            LogUtil.d("-----------------121-----------" + price);
            sum += price;
        }

        if (size < list_shopcart.size()) {
            isChange = true;
            binding.checkbox.setChecked(false);
        } else {
            isChange = false;
            binding.checkbox.setChecked(true);
        }
        binding.tvTotalprice.setText("￥" + Utils.numberPointTwo(sum));
    }

    public void onEventMainThread(SelectedPrice event) {
        double sum = 0.0;
        map = adapter.getMap();
        for (int i = 0; i < list_shopcart.size(); i++) {
            if (map.get(i)) {
                sum += adapter.calculateItemPrice(i, Double.parseDouble(list_shopcart.get(i).getShopCartPrice()));
            }
        }
        LogUtil.d("sum===========>" + sum);
        binding.tvTotalprice.setText("￥" + Utils.numberPointTwo(sum));
    }

    /**
     * 结算
     *
     * @param view
     */
    public void selectPatType(View view) {
        ViewConstant.list_local_cart.clear();
        for (int i = 0; i < list_shopcart.size(); i++) {
            if (map.get(i)) {
                ShopLocalListBean bean = new ShopLocalListBean();
                bean.setProduct_id(list_shopcart.get(i).getShopProductId());
                bean.setProduct_count(adapter.getShopcartAmountMap().get(i));
                bean.setProduct_title(list_shopcart.get(i).getShopCartTitle());
                bean.setProduct_oprice(Double.parseDouble(list_shopcart.get(i).getShopCartOPrice()));
                bean.setProduct_image(list_shopcart.get(i).getShopCartImgUrl());
                bean.setProduct_price(Double.parseDouble(list_shopcart.get(i).getShopCartPrice()));
                ViewConstant.list_local_cart.add(bean);
            }
        }
//        Gson gson=new Gson();
//        LogUtil.d("ddddddddddddddddddddddddd==========>"+gson.toJson(ViewConstant.list_local_cart));

        Bundle bundle = new Bundle();
        bundle.putString("totalprice", binding.tvTotalprice.getText().toString());
        GenericFragmentActivity.start(getActivity(), CartDetailFragment.class, bundle);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            init();
            adapter.notifyDataSetChanged();
        } else {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        event.unregister(this);
    }
}